import { Component } from 'react'
import Taro from '@tarojs/taro'
import {
  View,
  Text,
  Image,
  RadioGroup,
  Radio,
  Navigator,
} from '@tarojs/components'
import { AtLoadMore } from 'taro-ui'

import * as api from 'src/api'
import { EVENT_CHECK_ADDRESS } from 'src/constants'
import withPage from 'src/utils/withPage'

import './index.scss'

type IProps = {}

type IState = {
  addressList: any[]
  listStatus?: 'more' | 'loading' | 'noMore'
}

interface Index {
  props: IProps
  state: IState
  fromConfirm: boolean
}

@withPage()
class Index extends Component {
  state: IState = {
    addressList: [],
    listStatus: 'more',
  }

  onLoad(options) {
    this.fromConfirm = !!options.from_confirm
  }

  componentDidShow() {
    this.getAddressList()
  }

  async onPullDownRefresh() {
    await this.getAddressList()
    Taro.stopPullDownRefresh()
  }

  getAddressList = async () => {
    this.setState({ listStatus: 'loading' })
    const res = await api.getAddressList()
    const list = res.list || []
    this.setState({
      addressList: list,
      listStatus: 'noMore',
    })
  }

  handleClickDefault = async (e) => {
    await api.setAddressDefault(e.detail.value)
    Taro.showToast({ title: '设置成功', icon: 'success' })
  }

  handleEditAddress = (id) => {
    Taro.navigateTo({
      url: `/pages/address/index?id=${id}`,
    })
  }

  handleDeleteAddress = async (id) => {
    await api.delAddress(id)
    Taro.showToast({
      title: '删除成功',
      icon: 'success',
      complete: this.getAddressList,
    })
  }

  addWxAddress = () => {
    let that = this
    Taro.authorize({
      scope: 'scope.address',
      success: function () {
        Taro.chooseAddress({
          success: function (res) {
            api
              .editAddress({
                address: {
                  province: res.provinceName,
                  city: res.cityName,
                  district: res.countyName,
                  cityId: 0,
                },
                realName: res.userName,
                postCode: res.postalCode,
                phone: res.telNumber,
                detail: res.detailInfo,
                id: 0,
                isDefault: true,
              })
              .then(() => {
                Taro.showToast({
                  title: '添加成功',
                  icon: 'success',
                  complete: that.getAddressList,
                })
              })
          },
          fail: function (res) {
            if (res.errMsg === 'chooseAddress:fail cancel') {
              Taro.showToast({ title: '取消选择', icon: 'none' })
            }
          },
        })
      },
      fail: function () {
        Taro.showModal({
          title: '您已拒绝导入微信地址权限',
          content: '是否进入权限管理，调整授权？',
          success(res) {
            if (res.confirm) {
              Taro.openSetting()
            }
          },
        })
      },
    })
  }

  handleChecke = (item) => {
    if (this.fromConfirm) {
      Taro.eventCenter.trigger(EVENT_CHECK_ADDRESS, item)
      Taro.navigateBack()
    }
  }

  render() {
    const { addressList, listStatus } = this.state
    return (
      <View>
        <Image
          className="address-list-line"
          src={require('src/static/images/line.jpg')}
        ></Image>
        <RadioGroup className="address-list" onChange={this.handleClickDefault}>
          {addressList.map((item) => (
            <View className="address-item" key={item.id}>
              <View onClick={() => this.handleChecke(item)}>
                <View className="address-name">
                  {`收货人：${item.realName} ${item.phone}`}
                </View>
                <View className="address-describe">
                  {`收货地址：${item.province}${item.city}${item.district}${item.detail}`}
                </View>
              </View>
              <View className="address-actions at-row at-row__justify--between at-row__align--center">
                <Radio color="#e93323" value={item.id} checked={item.isDefault}>
                  设为默认
                </Radio>
                <View className="address-btns">
                  <View onClick={() => this.handleEditAddress(item.id)}>
                    <View className="at-icon at-icon-edit"></View>
                    <Text>编辑</Text>
                  </View>
                  <View onClick={() => this.handleDeleteAddress(item.id)}>
                    <View className="at-icon at-icon-trash"></View>
                    <Text>删除</Text>
                  </View>
                </View>
              </View>
            </View>
          ))}
        </RadioGroup>
        <AtLoadMore status={listStatus} noMoreTextStyle={{ fontSize: 12 }} />
        <View className="address-footer at-row at-row__justify--between at-row__align--center">
          <Navigator
            className="address-add-btn"
            url="/pages/address/index"
            hoverClass="none"
          >
            添加新地址
          </Navigator>
          <View className="address-add-wx" onClick={this.addWxAddress}>
            导入微信地址
          </View>
        </View>
      </View>
    )
  }
}

export default Index
